package com.tanhua.dubbomongo.api;

import com.tanhua.dubbointerface.api.MovementApi;
import com.tanhua.dubbomongo.utills.IdWorker;
import com.tanhua.dubbomongo.utills.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TimeLineService timeLineService;
    /**
     * 发布动态
     * @param movement
     */
    @Override
    public void publish(Movement movement) {
        //补充对象数据
        Long pid = idWorker.getNextId("movement");

        //通过保存操作以后会自动给主键id赋值
        try {
            movement.setPid(pid);
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //查询当前用户的好友数据
//            Criteria criteria = Criteria.where("userId").is(movement.getUserId());
//            Query query = new Query(criteria);
//            List<Friend> friends = mongoTemplate.find(query, Friend.class);
//            for (Friend friend : friends) {
//                MovementTimeLine movementTimeLine = new MovementTimeLine();
//                movementTimeLine.setMovementId(movement.getId());
//                movementTimeLine.setUserId(movement.getUserId());
//                movementTimeLine.setCreated(movement.getCreated());
//                movementTimeLine.setFriendId(friend.getUserId());
//                mongoTemplate.save(movementTimeLine);
//            }
             timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            //暂时不做事务处理
            e.printStackTrace();
        }

    }

    @Override
    public PageResult getMovementsVo(Long userId, int page, int size) {
        //过滤条件
        Query query = new Query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("created"))).limit(size).skip((page-1)*size);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        long counts = mongoTemplate.count(query, Movement.class);
        PageResult pageResult = new PageResult(page,size,counts,list);
        return pageResult;
    }

    @Override
    public List<Movement> getFriendsMovements(int page, int size, Long userId) {
        Query query = new Query(Criteria.where("friendId").is(userId));

        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        List<Movement> movements= new ArrayList<>();
        for (MovementTimeLine movementTimeLine : movementTimeLines) {
            Query q = new Query(Criteria.where("_id").is(movementTimeLine.getMovementId()));
            Movement one = mongoTemplate.findOne(q, Movement.class);
            movements.add(one);
        }
        return movements;
    }

    /**
     * 获取随机动态
     *
     *
     * @param size 分页大小
     * @return 这里直接返回PageResult对象
     */
    @Override
    public List<Movement> getRandomMovements(int size) {
        TypedAggregation aggregation =  TypedAggregation.newAggregation(Movement.class, Aggregation.sample(size));
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(aggregation, Movement.class);
        return aggregate.getMappedResults();
    }

    /**
     * 通过PID获取推荐动态数据
     * @param pIds PID集合
     * @return  返回动态数据集合
     */
    @Override
    public List<Movement> getRecommendMovements(List<Long> pIds) {
        Query query = new Query(Criteria.where("pid").in(pIds));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;
    }

    /**
     * 通过动态id查询单条动态
     * @param id
     * @return
     */
    @Override
    public Movement getMovementByID(String id) {
        Query query = new Query(Criteria.where("_id").is(id));

        return mongoTemplate.findOne(query,Movement.class);
    }


}